import axios from 'axios'
import router from '/@/router'
import { ElMessage } from 'element-plus'

const http = axios.create({
	baseURL: 'http://localhost:9001',
	timeout: 1000 * 30,
	withCredentials: true,
	headers: {
		'Content-Type': 'application/json; charset=utf-8'
	}
})

/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
    console.log('请求拦截:',config)
	let accessToken = localStorage.getItem("accessToken");
    console.log(accessToken)
	if (accessToken) {
		config.headers.accessToken = encodeURIComponent(accessToken);
	}
	return config
}, error => {
	return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(async response => {
    console.log('响应拦截:',response)
	if (response.data.code == 200) {
		return response.data.data;
	} else if (response.data.code == 400) {
		router.replace("/login");
	} else if (response.data.code == 401) {
		console.log("token失效，尝试重新获取")
		router.replace("/login");
	} else {
		ElMessage({
			message: response.data.message,
			type: 'error',
			duration: 1500,
			customClass: 'element-error-message-zindex'
		})
		return Promise.reject(response.data)
	}
}, error => {
    console.log('响应异常：',error)
	switch (error.response.status) {
		case 400:
			ElMessage({
				message: error.response.data,
				type: 'error',
				duration: 1500,
				customClass: 'element-error-message-zindex'
			})
			break
		case 401:
			router.replace("/login");
			break
		case 402:
			ElMessage({
				message: '参数错误，请检查参数后再试',
				type: 'error',
				duration: 1500,
				customClass: 'element-error-message-zindex'
			})
			break
		case 405:
			ElMessage({
				message: 'http请求方式有误',
				type: 'error',
				duration: 1500,
				customClass: 'element-error-message-zindex'
			})
			break
		case 404:
		case 500:
			ElMessage({
				message: '系统繁忙，请稍后再试',
				type: 'error',
				duration: 1500,
				customClass: 'element-error-message-zindex'
			})
			break
		case 501:
			ElMessage({
				message: '服务器不支持当前请求所需要的某个功能',
				type: 'error',
				duration: 1500,
				customClass: 'element-error-message-zindex'
			})
			break
	}

	return Promise.reject(error)
})

export default http